#encoding=utf8
from sklearn.cluster import DBSCAN
import numpy as np
from sklearn import metrics
import math
from sklearn.metrics.pairwise import paired_distances
from sklearn.preprocessing import StandardScaler
import sklearn.datasets as ds
import matplotlib.pyplot as plt
import matplotlib.colors


#x , y 都是是经纬度
#egg.   x = [121.446309,31.22367242]
def calGCJ02Distance(x,y):
    lat1 = x[1]
    lng1 = x[0]
    lat2 = y[1]
    lng2 = y[0]
    rlat1 = math.radians(lat1)
    rlat2 = math.radians(lat2)
    a = rlat1 - rlat2
    b = math.radians(lng1) - math.radians(lng2)
    s = 2 * math.asin(math.sqrt(
        math.pow(math.sin(a/2), 2) + math.cos(rlat1)*math.cos(rlat2)*math.pow(math.sin(b/2), 2)))
    return s * 6372797.0

def calGCJ02Distance_metric(x , y):
    fp1 = [(float)(x[0]),(float)(x[1])]
    fp2 = [(float)(y[0]),(float)(y[1])]
    return calGCJ02Distance(fp1,fp2)

if __name__ == "__main__":

    ############################
    #fake data
    matplotlib.rcParams['font.sans-serif'] = [u'SimHei']
    matplotlib.rcParams['axes.unicode_minus'] = False
    N = 100
    centers = [[1, 2], [-1, -1], [1, -1], [-1, 1]]
    fakedata, labels_true = ds.make_blobs(N, n_features=2, centers=centers, cluster_std=[0.5, 0.25, 0.7, 0.5], random_state=0)
    fakedata = StandardScaler().fit_transform(fakedata)
    print fakedata

    #############################
    #real data

    p1 = [121.446309,31.22367242]
    p2 = [121.446308,31.22367241]
    p3 = [121.446308,31.22367240]

    p4 = [121.416581,31.219042]
    p5 = [121.416581,31.219041]
    p6 = [121.416581,31.219040]
    p7 = [121.416580,31.219038]

    p8 = [120.446308,31.12367240]

    print paired_distances(p1,p2,metric=calGCJ02Distance_metric)

    dataset = [p1 ,p2,p3,p4,p5,p6,p7,p8]
    dataset = np.array(dataset)
    dbscan = DBSCAN(eps=10, min_samples=3,metric=calGCJ02Distance_metric)
    dbscan.fit(dataset)
    labels = dbscan.labels_
    print labels
    core_samples_mask = np.zeros_like(dbscan.labels_, dtype=bool)
    core_samples_mask[dbscan.core_sample_indices_] = True
    print core_samples_mask

    n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
    print('Estimated number of clusters: %d' % n_clusters_)
    print("Silhouette Coefficient: %0.3f"
          % metrics.silhouette_score(dataset, labels))

    plt.figure(figsize=(12, 8), facecolor='w')
    plt.suptitle(u'DBSCAN聚类', fontsize=20)
    unique_labels = set(labels)
    colors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels)))
    for k, col in zip(unique_labels, colors):
        if k == -1:
            # Black used for noise.
            col = 'k'

        class_member_mask = (labels == k)

        xy = dataset[class_member_mask & core_samples_mask]
        plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,
                 markeredgecolor='k', markersize=14)

        xy = dataset[class_member_mask & ~core_samples_mask]
        plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,
                 markeredgecolor='k', markersize=6)

    plt.title('Estimated number of clusters: %d' % n_clusters_)
    plt.show()

